package org.sbbs.base.searcher.impl;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.sbbs.base.searcher.SearchFilter;
import org.sbbs.base.searcher.SearchOperator;
import org.sbbs.base.searcher.SearchRule;
import org.springframework.util.Assert;

public class PropertySearchFilter extends SearchFilter {
	public static final String GROUPON_FILTER_KEY = "groupon_";// and 和 or
	// ，如果没有或者都不是则默认为and
	public static final String GROUPON_OR = "or";// and 和 or
	// ，如果没有或者都不是则默认为and
	private static final String FILTER_PREFIX = "filter_";

	public static SearchFilter BuildSearchFilter(HttpServletRequest req) {
		Map<String, Object> filterParamMap = getParametersStartingWith(req,
				FILTER_PREFIX);
		String groupon = req.getParameter(GROUPON_FILTER_KEY);
		if (groupon != null && groupon.equalsIgnoreCase(GROUPON_OR))
			groupon = "or";
		else
			groupon = "and";
		List srList = new ArrayList();
		for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) {
			String filterName = entry.getKey();
			String value = (String) entry.getValue();
			// 如果value值为空,则忽略此filter.
			if (StringUtils.isNotBlank(value)) {
				SearchRule sr = buildSearchRule(filterName, value);
				srList.add(sr);
			}
		}
		PropertySearchFilter psf = new PropertySearchFilter();
		psf.setMultiSearch(true);
		psf.setGroupOp(groupon);
		psf.setRules(srList);
		return psf;

	}

	private static SearchRule buildSearchRule(final String filterName,
			final String value) {

		String firstPart = StringUtils.substringBefore(filterName, "_");
		String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart
				.length());
		SearchOperator opr;
		try {
			// opr = Enum.valueOf(SearchOperator.class,
			// matchTypeCode.toLowerCase());
			opr = SearchOperator.valueOf(matchTypeCode.toLowerCase());

		} catch (RuntimeException e) {
			throw new IllegalArgumentException("filter名称" + filterName + ":"
					+ matchTypeCode + "没有按规则编写,无法得到属性比较类型.", e);
		}
		String propertyNameStr = StringUtils.substringAfter(filterName, "_");
		Assert.isTrue(StringUtils.isNotBlank(propertyNameStr), "filter名称"
				+ filterName + "没有按规则编写,无法得到属性名称.");
		SearchRule sr = new SearchRule();
		sr.setData(value);
		sr.setOp(opr.getOpr());
		sr.setField(propertyNameStr);
		return sr;

	}

	private static Map<String, Object> getParametersStartingWith(
			ServletRequest request, String prefix) {
		Assert.notNull(request, "Request must not be null");
		Enumeration paramNames = request.getParameterNames();
		Map<String, Object> params = new TreeMap<String, Object>();
		if (prefix == null) {
			prefix = "";
		}
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				String[] values = request.getParameterValues(paramName);
				if (values == null || values.length == 0) {
					// Do nothing, no values found at all.
				} else if (values.length > 1) {
					params.put(unprefixed, values);
				} else {
					params.put(unprefixed, values[0]);
				}
			}
		}
		return params;
	}
}
